<template>
  <div>
    <div style="height: 41px; line-height: 41px">
      <el-button
        type="primary"
        size="default"
        :disabled="!formData.entities[entIndex] || datasourceId != undefined"
        style="margin-top: 9px"
        @click="addEntityColumnRows"
      >
        <el-tooltip
          class="item"
          effect="dark"
          content="在实体列表中选中某个实体时，可以查看/编辑该实体下的字段信息"
          placement="top"
        >
          <el-icon><QuestionFilled /></el-icon>
          <!-- <i class="el-icon-question"></i> -->
        </el-tooltip>
        添加字段
      </el-button>
      <el-button type="primary" size="default" :disabled="true" style="margin-top: 9px"
      >刷新字段</el-button
      >
      <!-- <el-button type="primary" size="small" @click="exportAttr" icon="el-icon-download" style="margin-top: 9px;">
        字段模板导出
      </el-button>
      <el-button type="primary" size="small" @click="exportAttrCurrent" icon="el-icon-download"
                 style="margin-top: 9px;">
        导出字段
      </el-button> -->
      <!-- <el-upload style="display: inline-block;margin-left: 10px"
                 ref="upload"
                 action="action"
                 :show-file-list="false"
                 :on-change="readExcel"
                 :auto-upload="false">
        <el-button
          slot="trigger"
          icon="el-icon-upload"
          size="small"
          type="primary">
          导入字段
        </el-button>
      </el-upload> -->
    </div>
    <el-divider />
    <div v-if="formData.entities.length > 0" :style="{ height: winHeight + 'px' }">
      <el-table
        :data="columnsData"
        :maxHeight="winHeight"
        :height="winHeight"
        :row-style="{ height: '68px' }"
      >
        <el-table-column label="序号" type="index" align="center" width="50" />
        <el-table-column prop="formEntityColumnDesc" label="字段描述" align="center" width="189">
          <template #default="scope">
            <span
              v-if="
                (scope.row.formEntityColumnId && formData.deployed) || 'hide' == scope.row.status
              "
            >
              {{ scope.row.formEntityColumnDesc }}
            </span>
            <el-input
              v-else
              :disabled="
                scope.row.isSystem == 'Y' ||
                  scope.row.isAllowEdit == 'N' ||
                  datasourceId != undefined
              "
              autocomplete="off"
              placeholder="请输入内容"
              :id="scope.row.formEntityColumnName + 'formEntityColumnDesc' + scope.$index"
              clearable
              v-model="scope.row.formEntityColumnDesc"
              onkeyup="value=value.replace(/[\d]/g,'') "
              @blur="entBlur(scope.$index)"
              @input="
                attrNameFormat(
                  scope.row.formEntityColumnName + 'attrName' + scope.$index,
                  columnsData,
                  'formEntityColumnName',
                  scope.$index,
                  scope.row.formEntityColumnDesc
                )
              "
            />
          </template>
        </el-table-column>
        <el-table-column prop="formEntityColumnName" label="名称" align="center" width="188">
          <template #default="scope">
            <span
              v-if="
                (scope.row.formEntityColumnId && formData.deployed) || 'hide' == scope.row.status
              "
            >
              {{ scope.row.formEntityColumnName }}
            </span>
            <el-input
              v-else
              :disabled="
                scope.row.isSystem == 'Y' ||
                  scope.row.isAllowEdit == 'N' ||
                  datasourceId != undefined
              "
              autocomplete="off"
              placeholder="请输入内容"
              :id="scope.row.formEntityColumnName + 'attrName' + scope.$index"
              clearable
              v-model="scope.row.formEntityColumnName"
              @change="checkIsChinese"
              @blur="entBlur(scope.$index)"
            />
          </template>
        </el-table-column>
        <el-table-column prop="isRequired" label="必填" align="center" width="70">
          <template #default="scope">
            <span
              v-if="
                (scope.row.formEntityColumnId && formData.deployed) || 'hide' == scope.row.status
              "
            >{{ scope.row.isRequired === 'Y' ? '是' : '否' }}</span
            >
            <el-switch
              v-else
              :disabled="
                scope.row.isSystem == 'Y' ||
                  scope.row.isAllowEdit == 'N' ||
                  datasourceId != undefined
              "
              autocomplete="off"
              v-model="scope.row.isRequired"
              active-value="Y"
              inactive-value="N"
            />
          </template>
        </el-table-column>
        <el-table-column label="数据类型" align="center">
          <el-table-column prop="uiAdvise" label="UI建议" align="center" width="188">
            <template #default="scope">
              <span
                v-if="
                  (scope.row.formEntityColumnId && formData.deployed) || 'hide' == scope.row.status
                "
              >{{ formatDictLabel(dataTypeMap, scope.row.uiAdvise) }}</span
              >
              <el-select
                v-else
                :disabled="scope.row.isSystem == 'Y'"
                v-model="scope.row.uiAdvise"
                placeholder="请选择"
                @change="handleUiadviseChange(scope.row, scope.$index)"
              >
                <el-option
                  v-for="(item, index) in dataTypeTransform2Ui(scope.row.dataType)"
                  :key="index"
                  :label="item.chineseExplain"
                  :value="item.dictLabel"
                />
              </el-select>
            </template>
          </el-table-column>
          <el-table-column prop="format" label="格式" align="center" width="210">
            <template #default="scope">
              <div
                v-if="
                  'datetime' != scope.row.uiAdvise ||
                    !(
                      (scope.row.formEntityColumnId && formData.deployed) ||
                      'hide' == scope.row.status
                    )
                "
              >
                <el-select
                  v-if="'datetime' == scope.row.uiAdvise"
                  :disabled="
                    scope.row.isSystem == 'Y' ||
                      scope.row.isAllowEdit == 'N' ||
                      datasourceId != undefined
                  "
                  v-model="scope.row.format"
                  placeholder="请选择"
                >
                  <el-option
                    v-for="item in dateFormat"
                    :key="item.key"
                    :label="item.value"
                    :value="item.key"
                  />
                </el-select>
              </div>
              <span v-else>{{ formatDictLabel(dateFormat, scope.row.format) }}</span>
            </template>
          </el-table-column>
        </el-table-column>
        <el-table-column label="属性长度" align="center">
          <el-table-column prop="columnLength" label="整数长度" align="center" width="120">
            <template #default="scope">
              <span
                v-if="
                  (0 != scope.row.columnLength &&
                    scope.row.formEntityColumnId &&
                    formData.deployed) ||
                    ('1' == scope.row.status && 0 != scope.row.columnLength)
                "
              >{{ scope.row.columnLength }}</span
              >
              <div v-else>
                <el-input
                  :disabled="
                    scope.row.isSystem == 'Y' ||
                      scope.row.isAllowEdit == 'N' ||
                      datasourceId != undefined
                  "
                  v-if="
                    'datetime' != scope.row.uiAdvise &&
                      'clob' != scope.row.uiAdvise &&
                      'text' != scope.row.uiAdvise
                  "
                  autocomplete="off"
                  placeholder="请输入内容"
                  :id="scope.row.formEntityColumnName + 'attrLen' + scope.$index"
                  v-model="scope.row.columnLength"
                />
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="decimalLength" label="小数长度" align="center" width="120">
            <template #default="scope">
              <div
                v-if="
                  'number' != scope.row.uiAdvise ||
                    !(
                      (scope.row.formEntityColumnId && formData.deployed) ||
                      'hide' == scope.row.status
                    )
                "
              >
                <el-input
                  v-if="'number' == scope.row.uiAdvise"
                  autocomplete="off"
                  placeholder="请输入内容"
                  :id="scope.row.formEntityColumnName + 'decima' + scope.$index"
                  v-model="scope.row.decimalLength"
                  :disabled="
                    scope.row.isSystem == 'Y' ||
                      scope.row.isAllowEdit == 'N' ||
                      datasourceId != undefined
                  "
                />
              </div>
              <span v-else>{{ formatDictLabel(dateFormat, scope.row.decimalLength) }}</span>
            </template>
          </el-table-column>
        </el-table-column>
        <el-table-column prop="defaultValue" align="center" label="默认值" width="183">
          <template #default="scope">
            <el-input
              :disabled="
                scope.row.isSystem == 'Y' ||
                  scope.row.isAllowEdit == 'N' ||
                  datasourceId != undefined
              "
              v-if="'clob' != scope.row.uiAdvise && 'datetime' != scope.row.uiAdvise"
              placeholder="请输入内容"
              v-model="scope.row.defaultValue"
            />
            <el-date-picker
              v-if="'datetime' == scope.row.uiAdvise"
              type="datetime"
              :disabled="
                scope.row.isSystem == 'Y' ||
                  scope.row.isAllowEdit == 'N' ||
                  datasourceId != undefined
              "
              v-model="scope.row.defaultValue"
              :format="scope.row.format"
              :value-format="scope.row.format"
            />
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="160px" fixed="right">
          <template #default="scope">
            <el-button
              v-if="'hide' == scope.row.status"
              @click="recovery(scope.row)"
              size="default"
            >
              恢复
            </el-button>
            <div v-else>
              <el-button
                :disabled="
                  scope.row.isSystem == 'Y' ||
                    scope.row.isAllowEdit == 'N' ||
                    datasourceId != undefined
                "
                :class="[
                  'el-icon-delete-solid',
                  scope.row.isSystem == 'Y' ||
                    scope.row.isAllowEdit == 'N' ||
                    datasourceId != undefined
                    ? ''
                    : 'btnColor'
                ]"
                link
                @click="
                  handleCommand({
                    command: 'del',
                    index: scope.$index,
                    row: scope.row
                  })
                "
                size="default"
              >删除
              </el-button>
              <el-button
                class="el-icon-arrow-up"
                link
                :disabled="0 == scope.$index"
                @click="
                  handleCommand({
                    command: 'up',
                    row: scope.row,
                    index: scope.$index
                  })
                "
                size="default"
              >上升
              </el-button>
              <el-button
                class="el-icon-arrow-down"
                link
                :disabled="scope.$index == formData.entities[entIndex].columns.length - 1"
                @click="
                  handleCommand({
                    command: 'down',
                    row: scope.row,
                    index: scope.$index
                  })
                "
                size="default"
              >下降
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>
  </div>
</template>
<script>
// import import_methods from './import_methods'
import * as anvil from '@/utils/anvil'
// import dataType from './dataType'

export default {
  name: 'FormModelEntityColumn',
  // mixins: [import_methods],
  props: {
    attrTableData: {
      type: Object,
      default: () => {}
    },
    data: {
      type: Object,
      default: () => {}
    },
    entIndex: {
      type: Number,
      default: 0
    },
    datasourceId: {
      type: [String, undefined],
      default: undefined
    }
  },
  data() {
    return {
      hideAttr: [],
      tableData: [],
      dataTypeMap: [],
      dataTypeTransform: [],
      // dataType: [
      //   {key: "varchar", value: "文字", type:"input",valueType:'string'},
      //   {key: "bigint", value: "计数器", type:"counter",valueType:'number'},
      //   {key: "number", value: "数值", type:"number",valueType:'number'},
      //   {key: "datetime", value: "日期选择器", type:"datetime",valueType:'datetime'},
      //   // {key: "clob", value: "大文本", type:"textarea"},
      //   {key: "text", value: "长文本", type:"textarea",valueType:'string'},
      //   // {key: "money", value: "金额", type:"number"},
      //   {key: "select", value: "下拉框", type:"selects",valueType:'string'},
      //   {key: "radio", value: "单选", type:"radio",valueType:'string'},
      //   {key: "multiple", value: "多选", type:"checkbox",valueType:'listkv'},
      //   // {key: "email", value: "邮件", type:""},
      //   // {key: "url", value: "URL", type:""},
      //   // {key: "address", value: "地址", type:""},
      //   // {key: "phoneNumber", value: "手机号", type:""},
      // ],
      dateFormat: [
        { key: 'YYYY-MM-DD HH:mm:ss', value: '年-月-日 时:分:秒' },
        { key: 'YYYY-MM-DD HH:mm', value: '年-月-日 时:分' },
        { key: 'YYYY-MM-DD', value: '年-月-日' },
        { key: 'YYYY-MM', value: '年-月' },
        { key: 'YYYY', value: '年' }
        // {key: "HH:mm:ss", value: "HH:mm:ss"},
      ],
      winHeight: 969,
      formData: {}
    }
  },
  computed: {
    columnsData: function () {
      let columns = this.formData.entities[this.entIndex].columns.map((col, index) => {
        //  处理首次获取接口信息时字段转换
        if (!col.uiAdvise || !this.dataTypeMap.find((item) => item.dictLabel == col.uiAdvise)) {
          col.uiAdvise = this.dataType2DefaultUiAdvise(col.dataType)
        }
        this.handleUiadviseChange(col, index)
        return col
      })
      return columns
    }
  },
  watch: {
    data: {
      handler(newVal) {
        if (newVal) {
          this.formData = newVal
        }
      },
      deep: true,
      immediate: true
    },
    formData: {
      handler(e) {
        this.tableData = e
        this.$emit('update:data', e)
      },
      deep: true
    },
    entIndex: function (e) {
      this.index = e
    }
  },
  mounted() {
    this.getDataTypeTransform()
    this.getDataTypeMap()
    var e = this.winHeight - 280
    this.winHeight != e &&
      (window.innerHeight
        ? (this.winHeight = window.innerHeight)
        : document.body &&
          document.body.clientHeight &&
          (this.winHeight = document.body.clientHeight),
      (this.winHeight = this.winHeight - 280))
  },
  methods: {
    formatDictLabel(datas, value) {
      // var actions = [];
      // Object.keys(datas).some((key) => {
      //   if (datas[key].key == "" + value) {
      //     actions.push(datas[key].value);
      //     return true;
      //   }
      // });
      // return actions.join("");
      const item = datas.find((data) => data.dictLabel === value)
      const { chineseExplain } = item
      return chineseExplain || ''
    },
    entBlur(e) {
      this.$emit('entBlur', e)
    },
    attrNameFormat(e, t, n, i, o) {
      this.$emit('attrNameFormat', e, t, n, i, o)
    },
    checkIsChinese: function (e) {
      anvil.checkIsChinese(e)
    },
    handleUiadviseChange(e, t) {
      this.defaultDataFormat(e, t)
      // this.compTypeTransform2DataType(e, t);
    },
    defaultDataFormat(e, t) {
      var n = this.formData.entities[this.entIndex].columns
      ;(n[t].decimalLength = 0),
        (n[t].format = ''),
        'number' == e.uiAdvise ? (n[t].columnLength = 11) : ''
      'datetime' == e.uiAdvise
        ? (n[t].format = 'YYYY-MM-DD HH:mm:ss')
        : 'input' == e.uiAdvise
          ? (n[t].columnLength = 64)
          : 'counter' == e.uiAdvise && ((n[t].columnLength = 16), (n[t].decimalLength = 2))
    },
    handleCommand: function (e) {
      switch (e.command) {
        case 'del':
          this.deleteAttrRows(e.row, e.index)
          break
        case 'up':
          this.attrUp(e.row, e.index)
          break
        case 'down':
          this.attrDown(e.row, e.index)
          break
        default:
          break
      }
    },
    deleteAttrRows: function (e, t) {
      if (void 0 == e.formEntityColumnId)
        return (
          this.formData.entities[this.entIndex].columns.splice(t, 1),
          void this.formData.entities[this.entIndex].columns.forEach(function (e, n) {
            n == t && ((e.index = e.index - 1), ++t)
          })
        )
      this.isDel(e, t)
    },
    attrUp: function (e, t) {
      this.formData.entities[this.entIndex].columns[t].index =
        this.formData.entities[this.entIndex].columns[t].index - 1
      this.formData.entities[this.entIndex].columns[t - 1].index =
        this.formData.entities[this.entIndex].columns[t - 1].index + 1
      this.formData.entities[this.entIndex].columns = this.arrayMove(
        this.formData.entities[this.entIndex].columns,
        e,
        'up'
      )
    },
    attrDown: function (e, t) {
      this.formData.entities[this.entIndex].columns[t].index =
        this.formData.entities[this.entIndex].columns[t].index + 1
      this.formData.entities[this.entIndex].columns[t + 1].index =
        this.formData.entities[this.entIndex].columns[t + 1].index - 1
      this.formData.entities[this.entIndex].columns = this.arrayMove(
        this.formData.entities[this.entIndex].columns,
        e,
        'down'
      )
    },
    arrayMove: (e, t, n) => {
      if (((n = n || 'down'), !t || (t.constructor !== Object && t.constructor !== Array))) return e
      if ((t.constructor === Object && (t = [t]), 'up' == n))
        t.forEach((t) => {
          let n = e.indexOf(t, 1)
          if (n > 0) {
            let t = [...e]
            ;(t[n - 1] = e[n]), (t[n] = e[n - 1]), (e = t)
          }
        })
      else if ('down' == n)
        for (var i, o = t.length - 1; (i = t[o--]); ) {
          let t = e.indexOf(i, 0)
          if (t > -1 && t < e.length - 1) {
            let n = [...e]
            ;(n[t + 1] = e[t]), (n[t] = e[t + 1]), (e = n)
          }
        }
      return e
    },
    isDel: function (e, t) {
      // eslint-disable-next-line @typescript-eslint/no-this-alias
      var n = this
      n.formData.entities[n.entIndex].columns.splice(t, 1)
      n.formData.entities[n.entIndex].columns.forEach(function (e, n) {
        n == t && ((e.index = e.index - 1), ++t)
      })
      // this.formData.deployed ? a["a"].removeAttr(e).then(function (e) {
      //   e.data.state ? (n.$message({
      //     message: e.data.message + "，建模数据已更新！",
      //     type: "success"
      //   }), n.$emit("getFormData")) : n.$message({message: e.data.message, type: "error"})
      // }) : a["a"].deleteAttr(e.formEntityColumnId).then(function (e) {
      //   e.data.state ? n.$message({
      //     message: e.data.message,
      //     type: "success"
      //   }) : n.$message({message: e.data.message, type: "error"})
      // }).then(function () {
      //   n.formData.entities[n.entIndex].columns.splice(t, 1)
      //   n.formData.entities[n.entIndex].columns.forEach(function (e, n) {
      //     n == t && (e.index = e.index - 1, ++t)
      //   })
      //   a["a"].saveEntData(n.formData).then(function (e) {
      //   })
      // })
    },
    addEntityColumnRows() {
      let index = 0
      this.formData.entities[this.entIndex].columns.forEach((item, idx) => {
        if (item.isSystem == 'N' || item.isSystem == undefined) {
          index = idx
        }
      })
      var e = {
        index: index + 1,
        formEntityColumnDesc: '',
        formEntityColumnName: '',
        isRequired: 'Y',
        isHidden: 'N',
        isPrimaryKey: 'N',
        isPkAuto: 'N',
        sort: index + 1,
        uiAdvise: 'input',
        dataType: 'varchar',
        format: '',
        columnLength: 64,
        decimalLength: 0,
        defaultValue: ''
      }
      this.formData.entities[this.entIndex].columns.splice(index + 1, 0, e)
      // this.formData.entities[this.entIndex].columns.push(e);
    },
    // 获得后端数据结构的一层映射关系
    getDataTypeTransform() {
      this.getDicts('code_data_reflection_mod').then((response) => {
        this.dataTypeTransform = response.data
      })
    },
    getDataTypeMap() {
      this.getDicts('code_mod_reflection_data').then((response) => {
        this.dataTypeMap = response.data
      })
    },
    // 后端数据结构自身的一层转化
    dataTypeTransform2Self(dataType) {
      const trueDataTypeObj = this.dataTypeTransform.find((obj) => obj.dictLabel == dataType)
      return trueDataTypeObj ? trueDataTypeObj.dictValue : 'varchar'
    },
    // 获取后端数据结构到前端组件的映射关系
    dataTypeTransform2Ui(dataType) {
      const type = this.dataTypeTransform2Self(dataType)
      return this.dataTypeMap.filter((obj) => obj.dictValue == type)
    },
    // 设置默认uiadvise值，选取列表第一个符合数据结构的组件
    dataType2DefaultUiAdvise(dataType) {
      const list = this.dataTypeTransform2Ui(dataType)
      return list && list.length ? list[0].dictLabel : ''
    },
    compTypeTransform2DataType(e, t) {
      const dataType = this.dataTypeMap.find((item) => item.dictLabel === e.uiAdvise).dictValue
      this.formData.entities[this.entIndex].columns[t].dataType = dataType
    }
  }
}
</script>

<style lang="scss" scoped>
.form-entity-model {
  font-size: 12px;

  .el-date-editor.el-input,
  .el-date-editor.el-input__inner {
    width: 100%;
  }
}
.btnColor {
  color: red;
}
</style>
